/**
 * Created by admin on 2015/11/5.
 */
var AV = require('leanengine');
var async = require('async');
require('date-utils');
var cartCtrl =require('./cart.js');
//商品收藏的模型信息
var ActivitySignDayGive = AV.Object.extend("ActivitySignDayGive");
var UserCoupon = AV.Object.extend('UserCoupon');
var Coupons = AV.Object.extend('Coupons');
var User = AV.Object.extend('_User');
var PointFlow = AV.Object.extend('PointFlow');
var AmountFlow = AV.Object.extend('AmountFlow');
//ActivitySignDayUser
var SignDayUserM = AV.Object.extend('ActivitySignDayUser');
//ActivitySignDayDetail
var SignDayDetailM = AV.Object.extend('ActivitySignDayDetail');
//ActivitySignDayGive
var SignDayGiveM = AV.Object.extend('ActivitySignDayGive');
//ActivitySignDayRule
var SignDayGiveRuleM = AV.Object.extend('ActivitySignDayRule');
var ActivitySignDayDetail = AV.Object.extend('ActivitySignDayDetail');
var SignRule = AV.Object.extend('Sign');
var SupplyRule = AV.Object.extend('Supply');
//补签规则
var Supply = AV.Object.extend('Supply');

module.exports = {

    //发送满减券
    giveMJ:function(uid,limitMoney,cutMoney){
        var timestamp = Date.parse(new Date());
        var promise = new AV.Promise();
        async.waterfall([
            //判断优惠券是否存在
            function(callback){
                var query = new AV.Query(Coupons);
                query.equalTo("batchNo",'签到满减券满'+parseInt(limitMoney)+'元减'+parseInt(cutMoney)+'元');
                query.first().then(function(res){
                    if(res){
                        callback(null,res);
                    }else{
                        callback({code:1047,msg:"满减券未设置"});
                    }
                });
            },
            //发放满减
            function(res,callback){
                var takeCoupon = new UserCoupon();
                var endVaildTime=String(timestamp+7*3600*24*1000);
                var newCoupon={'uid':uid,'cid':res.get("batchNo"),GiveTime:new Date(),'validityEndPeriod':endVaildTime,'used':0,'status':1,coupon:res.attributes};
                takeCoupon.save(newCoupon).then(function(res){
                    callback(null,{code:0,msg:"发放成功",res:res});
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //发放优惠券
    giveCoupons:function(uid,realMoney){
        var timestamp = Date.parse(new Date());
        var promise = new AV.Promise();
        async.waterfall([
            //判断优惠券是否存在
            function(callback){
                var query = new AV.Query(Coupons);
                //console.log('签到发优惠券开始');
                query.equalTo("batchNo",'签到优惠券'+parseInt(realMoney)+'元');
                query.first().then(function(res){
                    if(res){
                        callback(null,res);
                    }else{
                        callback({code:1047,msg:"优惠券未设置"});
                    }
                });
            },
            //发放优惠券
            function(res,callback){
                var takeCoupon = new UserCoupon();
                var endVaildTime=String(timestamp+7*3600*24*1000);
                var newCoupon={'uid':uid,'cid':res.get("batchNo"),GiveTime:new Date(),'validityEndPeriod':endVaildTime,'used':0,'status':1,coupon:res.attributes};
                takeCoupon.save(newCoupon).then(function(res){
                    //console.log('签到发优惠券结束');
                    callback(null,{code:0,msg:"发放成功",res:res});
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //发放现金
    giveCash:function(uid,cash){
        var timestamp = Date.parse(new Date());
        var promise = new AV.Promise();
        async.waterfall([
            //判断优惠券是否存在
            function(callback){
                var query = new AV.Query(User);
                //query.equalTo("amount",'签到现金'+cash+'元');
                var newAmount = 0 ;
                var oldAmount = 0 ;
                query.get(uid).then(function(res){
                    if(res){
                        oldAmount = parseFloat(res.get('amount')) ;
                        newAmount = oldAmount+parseFloat(cash) ;
                        res.save({amount:newAmount}).then(function(){
                            callback(null,{user:res,newAmount:newAmount,oldAmount:oldAmount});
                        }).catch(function(err){
                            callback({code:-1,msg:'保存失败'});
                        });

                    }else{
                        callback({code:-1,msg:'用户不存在'});
                    }
                });
            },
            //发放现金
            function(res,callback){
                var amountFlow = new AmountFlow();
                amountFlow.save({
                    content: "连续签到奖励现金充值+"+cash+"元",
                    userid:uid,
                    newamount: parseFloat(cash),
                    beforeamount: res.oldAmount,
                    afteramount:res.newAmount
                }, {
                    success: function(post) {
                        callback(null,{code:0,msg:"发放成功",res:res});
                    },
                    error: function(post, error) {
                        callback(null,{code:0,msg:"发放失败",res:res});
                    }
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //发放积分
    givePoint:function (uid,point) {
        var promise = new AV.Promise();
        async.waterfall([
            //获取用户信息
            function(callback){
                var query = new AV.Query(User);
                //console.log(uid);
                query.get(uid).then(function(res){
                    var beforepoint = res.get('point');
                    res.set('point',beforepoint+parseInt(point));
                    res.save();
                    callback(null,parseInt(point),beforepoint);
                }).catch(function(err){
                    //console.log(err);
                    callback({code:1050,msg:"uid用户不存在",err:err});
                });
            },
            //记录积分流水
            function(point,beforepoint,callback){
                var pointFlow = new PointFlow();
                pointFlow.save({
                    content: "连续签到奖励积分+"+parseInt(point),
                    userid: uid,
                    newpoint: parseInt(point),
                    beforepoint: beforepoint,
                    afterpoint: beforepoint + parseInt(point)
                }, {
                    success: function(pointflow) {
                        callback(null,{code:0,msg:"领取积分奖励成功"});
                    },
                    error: function(pointflow, error) {
                        callback(null,{code:0,msg:"领取积分奖励成功,流水记录失败！"});
                    }
                });
            },
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //发放礼品券
    giveGiftToCart:function(userid,level){
        var promise = new AV.Promise();
        if(userid && level){
            async.waterfall([
                function(callback){
                    //根据level到rule表中查找对应的规则
                    var query = new AV.Query('ActivitySignDayRule');
                    query.equalTo('Day',parseInt(level.substring(1)));
                    //console.log('?????????????')
                    query.first().then(function(resDayRule){
                        if(resDayRule){
                            //console.log('================')
                            //console.log(resDayRule)
                            cartCtrl.insertProToCart(resDayRule.get('PID'),resDayRule.get('PSID'),1,userid,'3').then(function(resCart){
                                //console.log('///////////')
                                //console.log(resCart)
                                callback(null,resCart);
                            }).catch(function(err){
                                promise.resolve({code:-3,msg:'签到礼品加入购物车失败'});
                            })
                        }else{
                            promise.resolve({code:-2,msg:'不存在该奖品'});
                        }
                    });
                },
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve({code:0,msg:"已成功领取签到礼物"});
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('userid or GiftGiveID should not be empty');
        }
    },

    getSignDayValue:function(userid){
        var promise = new AV.Promise();
        if(!userid){
            return new AV.Promise.error("userid should not be empty!");
        }
        //获取签到数据  从user表中获取。如果没有，则返回一些默认值
        async.waterfall([
            function(callback){
                var query = new AV.Query(SignDayUserM);
                query.equalTo('Uid',userid);
                query.first().then(function(userInfo){
                    if(!userInfo || userInfo.length<1 || userInfo === "undefined"){
                        //没有任何签到记录，则直接返回一个值
                        return callback({code:1003,msg:'没有签到记录',AllSignDays:0,SignState:0});
                    }
                    //判断日期，当前日期与前一天的时间差是否为1天，如果是则显示正常数据。如果不是，则清空表内数据，返回连续签到天数为0
                    var year = userInfo.get('Year');
                    var month = userInfo.get('Month');
                    var day = userInfo.get('Day');
                    var lastTime = new Date(year+'-'+month+'-'+day+' 00:00:00'); //.toFormat('YYYY-MM-DD 00:00:00');
                    var now = new Date().toFormat('YYYY-MM-DD 00:00:00');
                    now=new Date(now);
                    var isOneDay = Math.floor((now - lastTime)/(24*3600*1000));
                    callback(null, isOneDay,userInfo);
                }).catch(function(err){
                    callback({code:9999,reason:err});
                });
                //callback(null, {code:1,msg:'success'});
            },
            function(isOneDay,userInfo,callback){
                //判断是否在一个周期内
                if(Math.floor((new Date(new Date().toLocaleDateString()+' 00:00:00') - new Date(userInfo.get('firstSignDate').toLocaleDateString()+' 00:00:00'))/(24*3600*1000))<=365){
                    var AllSignDays = userInfo.get('AllSignDays');
                }else{
                    var AllSignDays = 0;
                }
                //判断当天是否已签
                if(isOneDay >= 1){
                    callback(null, {code:0,msg:'',AllSignDays:AllSignDays,SignState:0,userInfo:userInfo});
                }else{
                    callback(null, {code:0,msg:'',AllSignDays:AllSignDays,SignState:1,userInfo:userInfo});
                }
            },
            function(data,callback){
                //获取该周期内已领取的礼物
                var query = new AV.Query(SignDayGiveM);
                query.equalTo('Uid',userid);
                query.equalTo('firstSignDate',data.userInfo.get('firstSignDate'));
                query.descending('createdAt');
                var list = new Array();
                query.find().then(function(res){
                    if(res){
                        async.eachSeries(res,function(eachRes,callback1){
                            var rule = eachRes.get('RuleDays')
                            list.push(global.initData.signGifts[rule]);
                            callback1(null, list);
                        },function(){
                            callback(null,{code:0,msg:'',AllSignDays:data.AllSignDays,SignState:data.SignState,GiftArray:list});
                        })
                    }else{
                        callback(null,{code:0,msg:'',AllSignDays:data.AllSignDays,SignState:data.SignState,GiftArray:list});
                    }
                });

            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /**
     * 签到操作1	Myron	setSginDayAction	!userid:String	code:int,msg:string
     * 说明：1、先判断ActivitySignDayUser表中是否存在信息
     *      2、如果存在：则进入第3步
     *         如果不存在：则插入一条记录，连续签到天数变为1，同时向ActivitySignDayDetail插入一条数据
     *      3、判断日期和当前是否相差一天
     *          3.1、如果是：
     *              3.1.1、判断是否为同一个月
     *                  如果是：则表示连续签到，连续签到增加1，同时向ActivitySignDayDetail插入一条数据
     *                  如果不是：则将MonthSignDay设为0，AllSignDay增加1，同时向ActivitySignDayDetail插入一条数据
     *          3.2、如果不是：清空记录（连续签到天数设置为0）
     * @param userid
     */
    setSignDayAction:function(userid,supplyDate){
        var now = supplyDate ;
        var promise = new AV.Promise();
        var firstSignDate = new Date();
        if(userid){
            async.auto({
                getGiftRule:function(callback){
                    var query = new AV.Query(SignDayGiveRuleM);
                    //console.log('======getGiftRule=====');
                    query.find().then(function(ruleInfo){
                        if(!ruleInfo || ruleInfo.length < 1){
                            return callback({code:1002,reason:'请先维护rule表'});
                        }
                        var ruleJson={};
                        async.eachSeries(ruleInfo,function(eachInfo,callback1){
                            ruleJson[eachInfo.get('Day')]= eachInfo;
                            callback1(null, ruleJson);
                        },callback(null,ruleJson));
                    }).catch(function(err){
                        callback({code:9998,reason:err});
                    });
                },
                //1、先判断ActivitySignDayUser表中是否存在信息
                hasUser:function(callback){
                    var query = new AV.Query(SignDayUserM);
                    query.equalTo('Uid',userid);
                    query.first().then(function(userInfo){
                        callback(null, userInfo);
                    }).catch(function(err){
                        callback({code:9997,reason:err});
                    });
                },
                updateUser:['hasUser',function(callback,results){
                    //不存在任何签到记录，则插入一条新记录。结束整个程序
                    var userInfo =results.hasUser;
                    //console.log('======updateUser start=====');
                    //console.log(userInfo);
                    var newMonthSignDay = 0;
                    var newAllSignDay = 0;
                    var newAllSignDays = 0;
                    if(!userInfo || userInfo.length<1){
                        var addNewUser = new SignDayUserM();
                        addNewUser.set('Uid',userid);
                        addNewUser.set('MonthSignDay',1);
                        addNewUser.set('AllSignDay',1);
                        addNewUser.set('AllSignDays',1);
                        //记录首签日
                        addNewUser.set('firstSignDate',firstSignDate);
                        addNewUser.set('Day',parseInt(now.getDate()));
                        addNewUser.set('Month',parseInt(now.getMonth()+1));
                        addNewUser.set('Year',parseInt(now.getFullYear()));
                        newMonthSignDay = 1 ;
                        newAllSignDay = 1 ;
                        addNewUser.save().then(function(){
                            //console.log('======updateUser end1=====');
                            callback(null, {Day:now.getDate(),Month:now.getMonth()+1,Year:now.getFullYear(),firstSignDate:firstSignDate,AllSignDay:newAllSignDay});
                        }).catch(function(err){
                            callback({code:9996,reason:err});
                        });
                    }else{
                        var AllSignDays = userInfo.get('AllSignDays');
                        var year = userInfo.get('Year');
                        var month = userInfo.get('Month');
                        var day = userInfo.get('Day');
                        var lastTime = new Date(year+'-'+month+'-'+day+' 00:00:00');
                        //var now = new Date().toFormat('YYYY-MM-DD 00:00:00');
                        now=new Date(new Date(now).toFormat('YYYY-MM-DD 00:00:00'));
                        //now-lastTime==1天
                        var isOneDay = Math.floor((now - lastTime)/(24*3600*1000));
                        if(isOneDay < 1){
                            //console.log('======updateUser end=====');
                            return callback({code:1001,reason:'已签过到'});
                        }
                        //判断是否为同一个周期
                        if(Math.floor((new Date(new Date().toLocaleDateString()+' 00:00:00') - new Date(userInfo.get('firstSignDate').toLocaleDateString()+' 00:00:00'))/(24*3600*1000))<=365){
                            newAllSignDays = AllSignDays+1;
                        }else{
                            newAllSignDays = 0;
                            userInfo.set('firstSignDate',firstSignDate);
                        }
                        userInfo.set('AllSignDays',newAllSignDays);
                        userInfo.set('Day',now.getDate());
                        userInfo.set('Month',(now.getMonth()+1));
                        userInfo.set('Year',now.getFullYear());
                        userInfo.save().then(function(){
                            //console.log('======updateUser end2=====');
                            callback(null, {Day:now.getDate(),Month:now.getMonth()+1,Year:now.getFullYear(),AllSignDays:newAllSignDays,});
                        }).catch(function(err){
                            callback({code:9995,reason:err});
                        });
                    }
                }],
                hasDetail:function(callback){
                    //向签到详情表中添加
                    var query = new AV.Query(SignDayDetailM);
                    query.equalTo('Uid',userid);
                    query.equalTo('Year',parseInt(now.getFullYear()));
                    //console.log('======hasDetail=====');
                    query.first().then(function(detail){
                        callback(null, detail);
                    }).catch(function(err){
                        callback({code:9994,reason:err});
                    });
                },
                updateDetail:['hasDetail','updateUser',function(callback,results){
                    var detail = results.hasDetail;
                    var date = results.updateUser;
                    //console.log('======updateDetail start=====');
                    if(!detail || detail.length<1 || detail === 'undefined'){
                        var addNewDetail = new SignDayDetailM();
                        addNewDetail.set('Uid',userid);
                        addNewDetail.addUnique('M'+(date.Month),date.Day);
                        addNewDetail.set('Year',parseInt(now.getFullYear()));
                        addNewDetail.set('firstSignDate',date.firstSignDate);
                        addNewDetail.save().then(function(){
                            callback(null, {code:0});
                        }).catch(function(err){
                            callback({code:9993,reason:err});
                        });
                    }else{
                        var array = new Array();
                        //console.log('=================1:');
                        //console.log(detail.get('M'+(date.Month)));
                        if(typeof (detail.get('M'+(date.Month))) != 'undefined' && detail.get('M'+(date.Month)) != null){
                            array =  detail.get('M'+(date.Month));
                        }else{
                            array =  [];
                        }
                        detail.addUnique('M'+(date.Month),date.Day);
                        detail.set('Year',parseInt(now.getFullYear()));
                        detail.save().then(function(){
                            //console.log('======updateDetail end2=====');
                            callback(null, {code:0,msg:'updateDetail success'});
                        }).catch(function(err){
                            callback({code:9993,reason:err});
                        });
                    }
                }],
                finalFunction:['updateDetail','getGiftRule','updateUser',function(callback,results){
                    callback(null, {code:0,msg:'Good && Success',updateUser:results.updateUser});
                }]
            },function(err,results){
                if(err){
                    //console.log('///////////////');
                    //console.log(err)
                    promise.reject(err);
                }else{
                    promise.resolve(results.finalFunction);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    setSignDayActionSupply:function(userid,supplyDate){
        var now = supplyDate ;
        var promise = new AV.Promise();
        var firstSignDate = new Date();
        if(userid){
            async.auto({
                getGiftRule:function(callback){
                    var query = new AV.Query(SignDayGiveRuleM);
                    //console.log('======getGiftRule=====');
                    query.find().then(function(ruleInfo){
                        if(!ruleInfo || ruleInfo.length < 1){
                            return callback({code:1002,reason:'请先维护rule表'});
                        }
                        var ruleJson={};
                        async.eachSeries(ruleInfo,function(eachInfo,callback1){
                            ruleJson[eachInfo.get('Day')]= eachInfo;
                            callback1(null, ruleJson);
                        },callback(null,ruleJson));
                    }).catch(function(err){
                        callback({code:9998,reason:err});
                    });
                },
                //1、先判断ActivitySignDayUser表中是否存在信息
                hasUser:function(callback){
                    var query = new AV.Query(SignDayUserM);
                    query.equalTo('Uid',userid);
                    query.first().then(function(userInfo){
                        callback(null, userInfo);
                    }).catch(function(err){
                        callback({code:9997,reason:err});
                    });
                },
                updateUser:['hasUser',function(callback,results){
                    //不存在任何签到记录，则插入一条新记录。结束整个程序
                    var userInfo =results.hasUser;
                    //console.log('======updateUser start=====');
                    var newMonthSignDay = 0;
                    var newAllSignDay = 0;
                    var newAllSignDays = 0;
                    if(!userInfo || userInfo.length<1){
                        var addNewUser = new SignDayUserM();
                        addNewUser.set('Uid',userid);
                        addNewUser.set('MonthSignDay',1);
                        addNewUser.set('AllSignDay',1);
                        addNewUser.set('AllSignDays',1);
                        //记录首签日
                        addNewUser.set('firstSignDate',firstSignDate);
                        addNewUser.set('Day',parseInt(now.getDate()));
                        addNewUser.set('Month',parseInt(now.getMonth()+1));
                        addNewUser.set('Year',parseInt(now.getFullYear()));
                        newMonthSignDay = 1 ;
                        newAllSignDay = 1 ;
                        addNewUser.save().then(function(){
                            //console.log('======updateUser end1=====');
                            callback(null, {Day:now.getDate(),Month:now.getMonth()+1,Year:now.getFullYear(),firstSignDate:firstSignDate,AllSignDay:newAllSignDay});
                        }).catch(function(err){
                            callback({code:9996,reason:err});
                        });
                    }else{
                        var AllSignDays = userInfo.get('AllSignDays');
                        var year = userInfo.get('Year');
                        var month = userInfo.get('Month');
                        var day = userInfo.get('Day');
                        var lastTime = new Date(year+'-'+month+'-'+day+' 00:00:00');
                        //var now = new Date().toFormat('YYYY-MM-DD 00:00:00');
                        now=new Date(new Date(now).toFormat('YYYY-MM-DD 00:00:00'));
                        //now-lastTime==1天
                        var isOneDay = Math.floor((now - lastTime)/(24*3600*1000));
                        if(isOneDay === 0){
                            //console.log('======updateUser end=====');
                            return callback({code:1001,reason:'已签过到'});
                        }
                        //判断是否为同一个周期
                        if(Math.floor((new Date(new Date().toLocaleDateString()+' 00:00:00') - new Date(userInfo.get('firstSignDate').toLocaleDateString()+' 00:00:00'))/(24*3600*1000))<=365){
                            newAllSignDays = AllSignDays+1;
                        }else{
                            newAllSignDays = 0;
                            userInfo.set('firstSignDate',firstSignDate);
                        }
                        userInfo.set('AllSignDays',newAllSignDays);
                        userInfo.save().then(function(){
                            //console.log('======updateUser end2=====');
                            callback(null, {Day:now.getDate(),Month:now.getMonth()+1,Year:now.getFullYear(),firstSignDate:firstSignDate,AllSignDays:newAllSignDays});
                        }).catch(function(err){
                            callback({code:9995,reason:err});
                        });
                    }
                }],
                hasDetail:function(callback){
                    //向签到详情表中添加
                    var query = new AV.Query(SignDayDetailM);
                    query.equalTo('Uid',userid);
                    query.equalTo('Year',parseInt(now.getFullYear()));
                    //console.log('======hasDetail=====');
                    query.first().then(function(detail){
                        callback(null, detail);
                    }).catch(function(err){
                        callback({code:9994,reason:err});
                    });
                },
                updateDetail:['hasDetail','updateUser',function(callback,results){
                    var detail = results.hasDetail;
                    var date = results.updateUser;
                    //console.log('======updateDetail start=====');
                    if(!detail || detail.length<1 || detail === 'undefined'){
                        //console.log("补签添加新数据");
                        var addNewDetail = new SignDayDetailM();
                        addNewDetail.set('Uid',userid);
                        addNewDetail.addUnique('M'+(date.Month),date.Day);
                        addNewDetail.set('Year',parseInt(now.getFullYear()));
                        //console.log(date.firstSignDate)
                        addNewDetail.set('firstSignDate',date.firstSignDate);
                        addNewDetail.save().then(function(){
                            callback(null, {code:0});
                        }).catch(function(err){
                            callback({code:9993,reason:err});
                        });
                    }else{
                        var array = new Array();
                        //console.log('=================1:');
                        //console.log(detail.get('M'+(date.Month)));
                        if(typeof (detail.get('M'+(date.Month))) != 'undefined' && detail.get('M'+(date.Month)) != null){
                            array =  detail.get('M'+(date.Month));
                        }else{
                            array =  [];
                        }
                        detail.addUnique('M'+(date.Month),date.Day);
                        detail.set('Year',parseInt(now.getFullYear()));
                        detail.save().then(function(){
                            //console.log('======updateDetail end2=====');
                            callback(null, {code:0,msg:'updateDetail success'});
                        }).catch(function(err){
                            callback({code:9993,reason:err});
                        });
                    }
                }],
                finalFunction:['updateDetail','getGiftRule','updateUser',function(callback,results){
                    callback(null, {code:0,msg:'Good && Success',updateUser:results.updateUser});
                }]
            },function(err,results){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(results.finalFunction);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error("userid should not be empty!");
        }
    },
    //想give表中添加记录
    /*
     TODO:测试通过
     */
    updateGive:function(uid,level,isReceived){
        //根据传过来的level，uid，插入新的记录
        //getGiftLevel
        var promise = new AV.Promise();
        var action = global.initData.signGifts[level].action;
        //var action = global.initData.signGift.level.action ;
        async.auto({
            getUserInfo:function(callback){
                var query = new AV.Query(SignDayUserM);
                query.equalTo('Uid',uid);
                query.first().then(function(res){
                    if(res){
                        callback(null, res.get('firstSignDate'));
                    }else{
                        callback(null, new Date());
                    }
                });
            },
            getRule:function(callback){
                //console.log('开始向give表中插入数据');
                var query = new AV.Query(SignDayGiveRuleM);
                query.equalTo("Day",level.substring(1));
                //console.log('开始向give表中插入数据'+level.substring(1));
                query.first().then(function(ruleInfo){
                    callback(null, ruleInfo);
                }).catch(function(err){
                    callback({code:9998,reason:err});
                });
            },
            giveGift:['getRule','getUserInfo',function(callback,results){
                var query = new SignDayGiveM();
                //console.log('开始向give表中插入数据'+new Date().getFullYear());
                //console.log('开始向give表中插入数据'+new Date().getMonth()+1);
                query.set('Uid',uid);
                query.set('Year',new Date().getFullYear());
                query.set('Month',new Date().getMonth()+1);
                query.set('firstSignDate',results.getUserInfo);
                query.set('Mold','0');
                query.set('RuleDays',level);
                if(action.gifts!=-1){
                    query.set('GiveGift',1);
                    query.set('GiveRule',results.id);
                }
                query.set('GiveMold',isReceived); // 是否领取
                query.save().then(function(){
                    //console.log('结束向give表中插入数据');
                    callback(null, {code:0});
                });
            }]
        },function(err,results){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(results.giveGift);
            }
        });
        return promise;
    },

    //获取日历中的签到天数数据
    getSignDayDetail:function(userid,year,month){
        var promise = new AV.Promise();
        var query = new AV.Query(ActivitySignDayDetail);
        var recod;
        var obj = {};
        obj['code'] = 0
        var date=new Date();
        query.equalTo('Uid',userid);
        query.equalTo('Year',parseInt(year));
        query.first().then(function(result){
            if(result){
                var m = "M"+month;
                recod = result.get(m);
                if(recod){
                    obj['data'] = recod;
                }else{
                    obj['data'] = [];
                }
                promise.resolve(obj);
            }else{
                obj['data'] = [];
                promise.resolve(obj);
            }
        }).catch(function(err){
            obj['data'] = [];
            promise.resolve(obj);
        });
        return promise;
    },
    //实物礼品领取,实物加入购物车
    setSignDayGiftCart:function(userid,GiftGiveID){
        var promise = new AV.Promise();
        if(userid && GiftGiveID){
            async.waterfall([
                //1.判断是否有未领取的奖品记录
                function(callback){
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('objectId',GiftGiveID);
                    query.equalTo('GiveMold',0);
                    query.first().then(function(res){
                        if(res){
                            callback(null,res);
                        }else{
                            promise.resolve({code:-1,msg:'不存在该奖品领取记录或改奖品已被领取'});
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                //2.如果有可以领取的记录，找到该奖品，并加入到购物车中，model为3表示签到送的
                function(res,callback){
                    var query = new AV.Query('ActivitySignDayRule');
                    query.get(res.get('GiveRule')).then(function(resDayRule){
                        if(resDayRule){
                            cartCtrl.insertProToCart(resDayRule.get('PID'),resDayRule.get('PSID'),1,userid,'3').then(function(resCart){
                                callback(null,res);
                            }).catch(function(err){
                                promise.resolve({code:-3,msg:'签到礼品加入购物车失败'});
                            })
                        }else{
                            promise.resolve({code:-2,msg:'不存在该奖品'});
                        }
                    }).catch(function(err){
                        callback(err);
                    });
                },
                //3.加入购物车后，将该奖品领取记录设置为已领取
                function(res,callback){
                    res.set('GiveMold',1);
                    res.set('GiveTime',new Date());
                    res.save().then(function(post) {
                        callback(null);
                    }).catch(function(err){
                        callback(err);
                    })
                }
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve({code:0,msg:"已成功领取签到礼物"});
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('userid or GiftGiveID should not be empty');
        }
    },

    //获取首签日的日期
    setFirstSignDate:function(uid){
        if(!uid){
            return new AV.Promise.error({code:220,msg:'用户id不存在'});
        }
        var promise = new AV.Promise();
        async.auto({
            getUserInfo:function(callback){
                //var querySignDayUser = new AV.Query(SignDayUserM);
                var querySignDayDetail = new AV.Query(SignDayDetailM);
                querySignDayDetail.equalTo('Uid',uid);
                querySignDayDetail.ascending('createdAt');
                querySignDayDetail.find().then(function(data){
                    if(data){
                        callback(null, data);
                    }else{
                        callback(null, {})
                    }
                });
            },
            //获取该用户的首签日
            getUserFirstSignDate:['getUserInfo',function(callback,results){
                var days = 0;
                var array = new Array();
                async.eachSeries(results.getUserInfo,function(eachInfo,callback1){
                    //计算两个日期间相差的天数mmSec / 3600000 / 24
                    //days = new Date().toLocaleDateString()+' 00:00:00';
                    days= Math.round((new Date(new Date().toLocaleDateString()+' 23:59:59') - new Date(new Date(eachInfo.createdAt).toLocaleDateString()+' 00:00:00'))/ 3600000 / 24);

                    if(days<=365){
                        //当前时间和目前的首签日在一个周期内，则不需要更新
                        array.push('同一个周期内，无需更新首签日');
                        callback1(null);
                    }else{
                        //否则，更新首签日
                        var querySignDayUser = new AV.Query(SignDayUserM);
                        querySignDayUser.equalTo('Uid',uid);
                        querySignDayUser.first().then(function(res){
                            res.save({'firstSignDate':eachInfo.createdAt}).then(function(){
                                array.push('更新首签日');
                                callback1(null);
                            });
                        })
                    }
                },function(){
                    callback(null, {code:0,msg:'success',array:array});
                })
            }],
            finalFun:['getUserFirstSignDate',function(callback,results){
                callback(null, results.getUserFirstSignDate);
            }]
        },function(err,results){
            if(err){
                promise.reject(err)
            }else{
                promise.resolve(results.finalFun);
            }
        });
        return promise;

    },

    //获取首签日的日期，批量更新,仅限2015年刚更新时使用
    setFirstSignDateAll:function(){
        var promise = new AV.Promise();
        async.auto({
            getUserInfo:function(callback){
                //var querySignDayUser = new AV.Query(SignDayUserM);
                var querySignDayDetail = new AV.Query(SignDayDetailM);
                querySignDayDetail.ascending('createdAt');
                querySignDayDetail.find().then(function(data){
                    if(data){
                        callback(null, data);
                    }else{
                        callback(null, {})
                    }
                });
            },
            //获取该用户的首签日
            getUserFirstSignDate:['getUserInfo',function(callback,results){
                var days = 0;
                var array = new Array();
                async.eachSeries(results.getUserInfo,function(eachInfo,callback1){
                    var querySignDayUser = new AV.Query(SignDayUserM);
                    querySignDayUser.equalTo('Uid',eachInfo.get('Uid'));
                    querySignDayUser.first().then(function(res){
                        res.save({'firstSignDate':eachInfo.createdAt}).then(function(){
                            array.push('更新首签日');
                            callback1(null);
                        });
                    });
                },function(){
                    callback(null, {code:0,msg:'success',array:array});
                })
            }],
            finalFun:['getUserFirstSignDate',function(callback,results){
                callback(null, results.getUserFirstSignDate);
            }]
        },function(err,results){
            if(err){
                promise.reject(err)
            }else{
                promise.resolve(results.finalFun);
            }
        });
        return promise;

    },

    //计算累计签到天数
    //1、根据首签日和当前日期，分别查找
    getAllSignDays:function(uid){
        if(!uid){
            return new AV.Promise.error({code:220,msg:'用户id不存在'});
        }
        var promise = new AV.Promise();
        async.auto({
            getUserInfo:function(callback){
                var querySignDayUser = new AV.Query(SignDayUserM);
                querySignDayUser.equalTo('Uid',uid);
                querySignDayUser.first().then(function(data){
                    if(data){
                        callback(null, data);
                    }else{
                        callback(null, [])
                    }
                });
            },
            getSignDetail:function(callback){
                var querySignDayDetail = new AV.Query(SignDayDetailM);
                querySignDayDetail.equalTo('Uid',uid);
                querySignDayDetail.find().then(function(data){
                    if(data){
                        callback(null, data);
                    }else{
                        callback(null, [])
                    }
                });
            },
            //获取该用户的首签日
            getUserFirstSignDate:['getUserInfo',function(callback,results){
                if(results.getUserInfo){
                    callback(null, {code:0,firtSignDate:results.getUserInfo.get('firtSignDate')});
                }else{
                    callback({code:-1,msg:'该用户还未曾签过到'});
                }
            }],
            getAllSignDays:['getSignDetail','getUserFirstSignDate',function(callback,results){
                if(results.getUserFirstSignDate.code === -1){
                    return callback(null, {code:-1,msg:'用户表问题'});
                }
                if(!results.getSignDetail){
                    return callback(null, {code:-1,msg:'该用户还未曾签到过'});
                }
                var startDate = {} ;
                var allSignDays = 0;

                async.eachSeries(results.getSignDetail,function(eachInfo,callback1){
                    for(var i= 1;i <= 12;i++){
                        startDate['M'+i] = eachInfo.get('M'+i) || [];
                        allSignDays += startDate['M'+i].length;
                    }
                    callback1(null,allSignDays);
                },function(){
                    callback(null, {code:0,msg:'success',allSignDays:allSignDays});
                });
            }],
            finalFun:['getAllSignDays',function(callback,results){
                callback(null, results.getAllSignDays.allSignDays);
            }]
        },function(err,results){
            if(err){
                promise.reject(err)
            }else{
                promise.resolve(results.finalFun);
            }
        });
        return promise;
    },
    //获取某一个用户的首签日
    getFirstSignDay:function(){
        if(!uid){
            return new AV.Promise.error({code:220,msg:'用户id不存在'});
        }
        var promise = new AV.Promise();

        async.auto({
            getUserInfo:function(callback){
                var querySignDayUser = new AV.Query(SignDayUserM);
                querySignDayUser.equalTo('Uid',uid);
                querySignDayUser.first().then(function(data){
                    if(data){
                        callback(null, data);
                    }else{
                        callback(null, [])
                    }
                });
            },
            getSignDetail:function(callback){
                var querySignDayDetail = new AV.Query(SignDayDetailM);
                querySignDayDetail.equalTo('Uid',uid);
                querySignDayDetail.find().then(function(data){
                    if(data){
                        callback(null, data);
                    }else{
                        callback(null, [])
                    }
                });
            },
            //获取该用户的首签日
            getUserFirstSignDate:['getUserInfo',function(callback,results){
                if(results.getUserInfo){
                    callback(null, {code:0,firtSignDate:results.getUserInfo.get('firtSignDate')});
                }else{
                    callback({code:-1,msg:'该用户还未曾签过到'});
                }
            }],
            getAllSignDays:['getSignDetail','getUserFirstSignDate',function(callback,results){
                if(results.getUserFirstSignDate.code === -1){
                    return callback(null, {code:-1,msg:'用户表问题'});
                }
                if(!results.getSignDetail){
                    return callback(null, {code:-1,msg:'该用户还未曾签到过'});
                }
                var startDate = {} ;
                var allSignDays = 0;

                async.eachSeries(results.getSignDetail,function(eachInfo,callback1){
                    for(var i= 1;i <= 12;i++){
                        startDate['M'+i] = eachInfo.get('M'+i) || [];
                        allSignDays += startDate['M'+i].length;
                    }
                    callback1(null,allSignDays);
                },function(){
                    callback(null, {code:0,msg:'success',allSignDays:allSignDays});
                });
            }],
            finalFun:['getAllSignDays',function(callback,results){
                callback(null, results.getAllSignDays.allSignDays);
            }]
        },function(err,results){
            if(err){
                promise.reject(err)
            }else{
                promise.resolve(results.finalFun);
            }
        });
        return promise;
    },
    //获取用户的累计签到天数
    getAllSignDays:function(uid){
        var promise = new AV.Promise();
        var querySignDayUser = new AV.Query(SignDayUserM);
        querySignDayUser.equalTo('Uid',uid);
        return querySignDayUser.first() ;
    },
    //补签规则
    getLevelOfBQ:function(uid,date){
        var promise = new AV.Promise();
        async.waterfall([
            function(callback){
                var query = new AV.Query(SignDayUserM);
                query.equalTo('Uid',uid);
                query.first().then(function(res){
                    callback(null, res.get('firstSignDate'))
                })
            },
            function(firstSignDate,callback){
                var query = new AV.Query(Supply);
                var level = '';
                var point = 0;
                //当前日期距离首签日的天数
                var days = Math.floor((new Date(new Date(date).toDateString()) - new Date(new Date(firstSignDate).toDateString())))/(24*3600*1000);
                //console.log('================='+days)
                if(parseInt(days)<=365 && parseInt(days)>=0){
                    query.find().then(function(res){
                        async.eachSeries(res,function(eachInfo,callback1){
                            var startDay = parseInt(eachInfo.get('begin_day'));
                            var endDay = parseInt(eachInfo.get('end_day'));
                            if(parseInt(startDay)<=parseInt(days) && parseInt(days)<=parseInt(endDay)){
                                level="D"+endDay ;
                                point = eachInfo.get('points')
                            }
                            callback1(null,point );
                        },function(){
                            callback(null, {code:0,point:point,days:days,firstSignDay:firstSignDate});
                        })
                    })
                }else{
                    return callback(null, {code:1,point:point,days:days,firstSignDay:firstSignDate})
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err)
            }else{
                promise.resolve(result);
            }
        });
        return promise;

    },
    //cutPointOfBQ 扣减积分
    cutPointOfBQ:function(date,uid,point){
        var promise = new AV.Promise();
        async.waterfall([
            function(callback){
                var query = new AV.Query(User);
                query.get(uid).then(function(res){
                    var newPoint = parseInt(res.get('point'))-parseInt(point);
                    res.save({point:newPoint}).then(function(){
                        callback(null, {code:0,userInfo:res,point:point,newPoint:newPoint,oldPoint:res.get('point')});
                    }).catch(function(){
                        callback(null,{code:1})
                    });
                }).catch(function(){
                    callback(null,{code:1})
                });
            },
            //记录积分流水
            function(user,callback){
                if(user.code === 0){
                    var pointFlow = new PointFlow();
                    pointFlow.save({
                        content: new Date(date).toFormat("YYYY/MM/DD")+"补签扣除积分-"+parseInt(user.point),
                        userid: uid,
                        newpoint: parseInt(user.newPoint),
                        beforepoint: user.oldPoint,
                        afterpoint: parseInt(user.newPoint)
                    }, {
                        success: function(pointflow) {
                            callback(null,{code:0,msg:"扣减成功"});
                        },
                        error: function(pointflow, error) {
                            callback(null,{code:0,msg:"扣减成功,流水记录失败！"});
                        }
                    });
                }else{
                    callback(null,{code:1});
                }

            },
        ],function(err,result){
            if(err){
                promise.reject(err)
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    //获取累计签到等级
    getLevelOfSignDays:function(allSignDays){
        var promise = new AV.Promise();
        var level = '' ;
        if(0<=allSignDays && allSignDays <=30){
            level = "D30" ;
        }else if(31<=allSignDays && allSignDays <=60){
            level = "D60" ;
        }else if(61<=allSignDays && allSignDays <=90){
            level = "D90" ;
        }else if(91<=allSignDays && allSignDays <=150){
            level = "D150" ;
        }else if(151<=allSignDays && allSignDays <=210){
            level = "D210" ;
        }else if(211<=allSignDays && allSignDays <=270){
            level = "D270" ;
        }else if(271<=allSignDays && allSignDays <=330){
            level = "D330" ;
        }else if(331<=allSignDays && allSignDays <=365){
            level = "D3650" ;
        }else{
            level = "D3650" ;
        }
        promise.resolve({code:0,level:level});
        return  promise;
    },
    //获取奖品等级
    getGiftLevel:function(allSignDay){
        //global.initData.signGift
        var test = global.initData.signGifts ;
        var promise = new AV.Promise();
        if(test.hasOwnProperty('D'+allSignDay)){
            promise.resolve({code:0,level:'D'+allSignDay});
        }else{
            promise.resolve({code:1,level:0});
        }
        return  promise;
    },
    //判断礼物是否已领取
    isRecievedGifts:function(userid,level){
        var promise = new AV.Promise();
        if(userid && level){
            async.waterfall([
                function(callback){
                    //根据level到rule表中查找对应的规则
                    var query = new AV.Query(ActivitySignDayGive);
                    query.equalTo('Uid',userid);
                    query.equalTo('RuleDays',level);
                    query.first().then(function(data){
                        if(data){
                            if(data.get("GiveMold") === 0 ){
                                callback(null, {code:0});
                            }else{
                                callback(null, {code:1});
                            }
                        }else{
                            callback(null, {code:2});
                        }

                    });
                },
            ],function(err,result){
                if(err){
                    promise.reject(err);
                }else{
                    promise.resolve(result);
                }
            });
            return promise;
        }else{
            return new AV.Promise.error('userid or GiftGiveID should not be empty');
        }
    },
    //获取用户表信息
    getUserInfo:function(uid){
        var promise = new AV.Promise();
        var query = new AV.Query(SignDayUserM);
        query.equalTo('Uid',uid);
        return query.first();
    },
    //获取用户表信息
    get_UserInfo:function(uid){
        var promise = new AV.Promise();
        var query = new AV.Query(User);
        return query.get(uid);
    },
    getSignDayRules:function(){
        var query = new AV.Query(SupplyRule);
        //query.ascending('points');
        return query.find();
    },
    //获取当前日期到首签日的时间差，返回补签类型和奖励类型，写到控制器层

    setTypeOfDay:function(date,firstSignDay){
        //var days= Math.round((new Date(new Date().toDateString()+' 23:59:59') - new Date(new Date(firstSignDay).toLocaleDateString()+' 00:00:00'))/ 3600000 / 24);

    }


};
